package sokoban;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;

public class SokobanCanvas extends GameCanvas implements Runnable {

	private GameMap gameMap;
	
	private volatile Thread t = null;

	public SokobanCanvas() {
		super(true);
	}

	public void stop() {
		t = null;
	}

	public void start() {
		t = new Thread(this);
		t.start();
	}
	
	public void restart(){
		stop();
		start();
	}
	
	public void run() {

		while (t == Thread.currentThread()) {
			if (gameMap != null && !gameMap.isGameFinished()) {
				checkInput();
			}
			updateScreen();
			try {
				Thread.sleep(100);
			} catch (Exception e) {
			}
		}
	}

	protected void checkInput() {
		int keyStates = getKeyStates();
		if (keyStates >= 0) {
			if ((keyStates & LEFT_PRESSED) != 0) {
				gameMap.HandleAction(Constants.MOVE_LEFT);
			} else if ((keyStates & RIGHT_PRESSED) != 0) {
				gameMap.HandleAction(Constants.MOVE_RIGHT);
			} else if ((keyStates & UP_PRESSED) != 0) {
				gameMap.HandleAction(Constants.MOVE_UP);
			} else if ((keyStates & DOWN_PRESSED) != 0) {
				gameMap.HandleAction(Constants.MOVE_DOWN);
			}
		}
	}

	public void updateScreen() {
		Graphics g = getGraphics();
		g.setColor(255, 255, 255);
		g.fillRect(0, 0, getWidth(), Constants.STATUS_BAR_HEIGHT);
		g.setColor(150, 150, 150);
		g.fillRect(0, Constants.STATUS_BAR_HEIGHT, getWidth(), getHeight()
				- Constants.STATUS_BAR_HEIGHT);
		if (gameMap != null) {
			g.setColor(0, 0, 0);
			g.drawString("Moves: " + gameMap.getNumOfMoves(),
					Constants.STATUS_TEXT_X, Constants.STATUS_TEXT_Y,
					Graphics.BOTTOM | Graphics.LEFT);
			gameMap.draw(g, getWidth(), getHeight());
			if (gameMap.isGameFinished()) {
				int x = getWidth() / 2 - Constants.SCORE_MESSAGE_WIDTH / 2;
				int y = getHeight() / 2 - Constants.SCORE_MESSAGE_HEIGHT / 2;
				g.setColor(0, 0, 0);
				g.fillRect(x, y, Constants.SCORE_MESSAGE_WIDTH,
						Constants.SCORE_MESSAGE_HEIGHT);
				g.setColor(255, 255, 255);
				g.drawString("Your score:", x + Constants.SCORE_MESSAGE_WIDTH
						/ 2, y + 10, Graphics.TOP | Graphics.HCENTER);
				g.drawString("" + gameMap.getNumOfMoves(), x
						+ Constants.SCORE_MESSAGE_WIDTH / 2, y + 30,
						Graphics.TOP | Graphics.HCENTER);
			}
		}
		flushGraphics();
	}

	public GameMap getGameMap() {
		return gameMap;
	}

	public void setGameMap(GameMap gameMap) {
		this.gameMap = gameMap;
	}
}
